import getLocationAuth from '@/utils/getLocationAuth.js' //开启定位方法
import listCar from './components/buyCar/buyCar.vue' //新车
import timLogin from '@/utils/timLogin.js'
import carMaintenance from './components/car_maintenance/car_maintenance.vue' //养车
import pageSwiper from './components/pyh-pageSwiper/pyh-pageSwiper.vue'
import pageSwiperItem from './components/pyh-pageSwiper/pyh-pageSwiper-item.vue'
const dayjs = require('@/utils/dayjs.js')
import {
	getUrlParam
} from '@/utils/common-api.js'
import {
	mapState
} from 'vuex'
export default {
	components: {
		listCar,
		carMaintenance,
		pageSwiper,
		pageSwiperItem
	},
	data() {
		return {
			descObj: {
				show: false,
				content: '',
			},
			// 扫码有订单显示弹窗
			showOrderModal: false,
			isScr: false,
			pageLading: false,
			isOpen: false, //下拉开关
			isLocation: false, //是否定位
			enable: true, //是否吸顶
			//tab样式
			activeItem: {
				'font-size': '32rpx'
			},
			//添加爱车列表
			specifAll: {
				brandlist: [], //品牌
				Serieslist: [], //系列
				Displacement: [], //排量
				Modelyear: [], //年款
				Configulist: [], //车子
			},
			isNew: false, //是否是新用户
			height: 0, //导航栏高度
			district: '', //区
			rangeValues3: [], //推荐筛选值
			swiperHight: 163,
			province: '', //省份
			searchKey: '', //搜索关键字
			city: '', //城市
			swiperCurrent: 0, //swiper当前页（要新车模块注释）
			statusBarHeight: 600, //swiper高度
			//siwper列表
			swiperList: [{
					name: '养车'
				},
				{
					name: '购车'
				},
			],
			token: '',
			postalCode: 0, //城市id
			headerHight: 0,
			isWashing: false, //是否在洗车中
			washCardId: '', //进行中的洗车订单信息
			washMachineId: '', //进行中的洗车订单信息
			washingTime: '00:01', //进行中的洗车订单信息
			diffTime: 0, //进行中的洗车订单信息
			washTimer: null, //洗车订单计时器
		}
	},
	computed: {
		...mapState({
			vuexDistrict: state => state.district,
			vuexCity: state => state.city,
			vuexScroll: state => state.scroll,
		}),
		//swiper(要新车模块打开)
		/* swiperCurrent() {
		  return this.$store.state.changeIndex
		}, */
		tabHight() {
			return Math.floor(Number(this.headerHight) / (uni.upx2px(Number(this.headerHight)) / Number(this
				.headerHight))) + 40 || 0
		},
		winWidth() {
			return Math.floor(Number(this.pmWidth) / (uni.upx2px(Number(this.pmWidth)) / Number(this
				.pmWidth))) - 1
		},
		isLogin() {

		},

		serviceNumber() {
			return this.$store.state.serviceNumber
		}
	},
	filters: {
		cutString(str, len) {
			if (str.length * 2 <= len) {
				return str
			}
			let strlen = 0
			let s = ''
			for (let i = 0; i < str.length; i++) {
				s = s + str.charAt(i)
				if (str.charCodeAt(i) > 128) {
					strlen = strlen + 2
					if (strlen >= len) {
						return s.substring(0, s.length - 1) + '...'
					}
				} else {
					strlen = strlen + 1
					if (strlen >= len) {
						return s.substring(0, s.length - 2) + '...'
					}
				}
			}
			return s
		},
	},
	onLoad() {
		if (getApp().globalData.url) {
			uni.navigateTo({
				url: getApp().globalData.url
			})
			getApp().globalData.url = ''
		}
		uni.$on('xinstall', () => {
			if (getApp().globalData.url) {
				uni.navigateTo({
					url: getApp().globalData.url
				})
				getApp().globalData.url = ''
			}
		})

		//是否显示红包框
		// this.token = uni.getStorageSync('token')
		// if (!this.token) {
		//   this.isNew = true
		//   uni.hideTabBar({
		//     animation: true
		//   })
		// }

		// 选择品牌，系列，排量，年款，车子
		uni.$on('carMaintenances', data => {
			Object.assign(this.specifAll, data)
			if (data.licenseplate && data.pageFrom === 'carMaintenances') {
				//添加爱车
				this.$refs.addCar.AddCar()
			}
		})
		//状态栏高度
		this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight * 2
		// this.height = (this.statusBarHeight + 96) * 2
		this.getLocation()
	},
	onUnload() {
		uni.$off('carMaintenances')
	},
	onShow() {
		let token = uni.getStorageSync('token')
		this.isWashing = false
		if (this.washTimer) {
			clearInterval(this.washTimer)
		}
		if (token) {
			// 已登录
			this.hasWashingOrder()
		}

		this.enable = true
		this.district = this.$store.state.district

		//#ifndef MP-WEIXIN
		if (this.$refs.pageSwiper) {
			this.$refs.pageSwiper.swiperTo(this.swiperCurrent)
		}
		//#endif
		if (this.$refs.addCar) {
			if (token) {
				this.$refs.addCar.GetCarList()
			}
			this.$refs.addCar.getMaintainStoreList()
		}

		//区间值以及typeid值
		uni.$on('rangeValues3', data => {
			this.rangeValues3 = data
			this.comunicationOff()
		})

		//登录
		if (this.$store.state.isSDKReady) {
			this.timReady()
		} else {
			timLogin(() => {
				this.timReady()
			})
		}
	},

	onReady() {
		this.$nextTick(() => {
			//获取导航栏高度
			const query = uni.createSelectorQuery().in(this)
			query.select('.nav-container').boundingClientRect(data => {
				// this.height = data.height
				this.height = data.height
			}).exec()
			//#ifndef MP-WEIXIN
			/* if(this.swiperCurrent===0){
			  this.$refs.addCar.getHight()
			}else{
			  this.$refs.refresh.getHight()
			} */
			this.getHight()
			//#endif
		})

	},
	onHide() {
		this.enable = false
		this.isWashing = false
		if (this.washTimer) {
			clearInterval(this.washTimer)
		}
	},
	methods: {
		getHight(e) {
			setTimeout(() => {
				if (this.swiperCurrent === 0) {

					this.headerHight = this.$refs.addCar.headerHight || 500
				} else {
					this.$nextTick(() => {
						this.pageLading = true
					})
					this.headerHight = this.$refs.refresh.headerHight || 500
				}
			}, 1000)

		},
		getLocation() {
			const location = uni.getStorageSync('addressList')
			//#ifdef APP-PLUS
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				success: res => {
					if (location) {
						if (location.city !== res.address.city) {
							this.city = res.address.city
							this.district = res.address.district
							this.isLocation = true
						} else {
							this.location()
						}
					} else {
						this.location()
					}
				},
				fail: () => {
					getLocationAuth()
				}
			})
			//#endif
			//#ifdef MP-WEIXIN
			let _this = this
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				success: resData => {
					uni.request({
						url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${resData.latitude},${resData.longitude}&key=LBOBZ-KSNKF-HIVJP-JXCC3-B3RRQ-ZUFKI`,
						success: async res => {
							let data = res.data.result.ad_info
							let obj = {
								city: data.city,
								province: data.province,
								district: data.district,
								postalCode: Number(data.adcode),
								lon: data.location.lng,
								lat: data.location.lat
							}
							await _this.getCityList(data.city, data.district)
							_this.$store.dispatch('changeAddress', obj)
							_this.district = data.district
							_this.city = data.city
							_this.province = data.province
							uni.setStorageSync('addressList', obj)
						}
					})
				},
				fail: () => {}
			})
			//#endif
		},
		//获取市区
		async getCityList(address, district) {
			try {
				const {
					data
				} = await this.$api.jsonData.regionaldistrict()
				let add = data.Item.find(item => item.name === district)
				this.postalCode = Number(add.id)

				/*   let that = this
			    data.Item.childlist.map(item1 => {
			      item1.childlist.map(item2 => {
			        if (item2.name === address) {
								item2.childlist.map(item3 =>{
									if(item3.name === district){
										that.postalCode = Number(item3.id)
									}
								})
			        }
			      })
			    }) */
			} catch (e) {

			}
		},
		//定位
		location() {
			//#ifdef APP-PLUS
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				success: async res => {
					await this.getCityList(res.address.city, res.address.district)
					let addArr = {
						city: res.address.city,
						province: res.address.province,
						district: res.address.district,
						postalCode: this.postalCode, //id
						lon: res.longitude, //经度
						lat: res.latitude
					}
					this.$store.dispatch('changeAddress', addArr)
					this.district = res.address.district
					this.city = res.address.city
					this.province = res.address.province
					uni.setStorageSync('addressList', addArr)
				},
				fail: () => {
					//判断是否定位
				}
			})
			//#endif
		},
		//切换地址
		changeAdd() {
			this.location()
			this.isLocation = false
		},
		order() {
			uni.navigateTo({
				url: '/pages_order/buy_order/buy_order'
			})
		},

		//登录
		login() {
			this.isNew = false
			uni.showTabBar({
				animation: true
			})
			uni.setStorage({
				key: 'launchFlag',
				data: false,
			})
			uni.navigateTo({
				url: '/pages_logins/login/login'
			})
		},
		//扫一扫
		saoyisao() {
			uni.scanCode({
				success: async res => {
					console.log(res)
					// let code = uni.getStorageSync('Ztc_C_USER_INFO').invitecode
					let that = this
					let token = uni.getStorageSync('token')
					//判断登录不能邀请
					let resObj = getUrlParam(res.result)
					console.log(resObj)
					if (resObj.code && token) {
						uni.showToast({
							title: '您已经是7迈车会员!',
							icon: 'none'
						})
						return false
					}
					//没有登录可以邀请好友
					if (resObj.code) {
						let code = resObj.code
						console.log(code)
						uni.setStorageSync('invitationcode', code)
						that.$u.debounce(that.login, 1000)
						/* uni.navigateTo({
						  url: encodeURI('/pages_common/sign/sign?index=5' + '&id=' + res.result)
						}) */
						return false
					}
					// 微信小程序 :
					// #ifdef MP-WEIXIN
					if (res.result && res.result.indexOf('carwash_globalche') > -1) {
						// 后台管理系统二维码跳转逻辑
						if (resObj.isCarWashStationShare) {
							let p =
								`?isCarWashStationShare=${resObj.isCarWashStationShare}&siteId=${resObj.siteId}&storeId=${resObj.storeId}`
							uni.navigateTo({
								url: '/pages_commodity/selfWash/carwash_globalche/carwash_globalche' +
									p
							})
							return
						}
						// 商户端分享二维码跳转逻辑
						if (resObj.id && resObj.siteId) {
							let p = `?siteId=${resObj.siteId}&id=${resObj.id}`
							uni.navigateTo({
								url: '/pages_commodity/selfWash/carwash_globalche/carwash_globalche' +
									p
							})
							return
						}
					}
					// #endif
					//判断是否登录
					if (!token) {
						this.$u.toast('请登录！')
						this.$u.debounce(this.login, 1000)
						return false
					}
					//排队二维码
					if (res.result.indexOf('lineUp') > -1 && resObj.state * 1 === 1) {
						uni.navigateTo({
							url: '/pages_commodity/lineUp/lineUp?storeId=' + resObj.id
						})
						// 签字二维码
					} else if (res.result.indexOf('sign') > -1 && resObj.state) {
						uni.navigateTo({
							url: '/pages_common/sign/sign?state=' + resObj.state + '&id=' + resObj
								.id
						})
						// 洗车二维码
					} else if (res.result.indexOf('pages_commodity') > -1 && resObj.type && resObj.type ===
						'existingOrder') {
						// 根据接口判断当前是否有订单
						let isWashing = false
						uni.showLoading({
							title: '加载中'
						})
						this.$api.selfServiceCarWash.getCheckMyInProgressOrder().then(async res => {
							uni.hideLoading()
							if (res.code === 200 && res.data && res.data
								.selfServiceCarWashOrder) {
								isWashing = true
							}
							// 有洗车订单
							if (isWashing) {
								// 1、扫自己当前用的机器就直接跳转洗车页面
								if (resObj.id === this.washMachineId) {
									this.orderDetial()
									// 2、扫其他机器的二维码,弹窗提示已有订单,是否结束，是：结束该订单 否：回到订单洗车页
								} else {
									this.showOrderModal = true
								}
							} else {
								// 请求后端接口,确认机器是否可用
								let result =
									await this.$api.selfServiceCarWash.CheckMachineAndOrder({
										wash_Machine_Id: resObj.id,
									})
								if (result.data.isAvailable) {
									this.$store.commit('purchaseChannel', true)
									uni.navigateTo({
										url: `/pages_commodity/selfWash/existingOrder?id=${resObj.id}`
									})
								} else {
									this.descObj.content = result.data.returnMessage
									this.descObj.show = true
								}
							}
						}).catch(err => {
							console.log(err)
							uni.hideLoading()
						})
					} else {
						this.$u.toast('二维码有误')
					}
				}
			})
		},
		//遮罩层
		clickMask() {
			this.isNew = false
			uni.showTabBar({
				animation: true
			})
		},
		//tab切换
		change(e) {
			this.$store.commit('setChangeIndex', e)
			//#ifndef MP-WEIXIN
			if (e === 0) {
				this.$refs.addCar.getHight()
				this.headerHight = this.$refs.addCar.headerHight
			} else {
				this.$refs.refresh.getHight()
				this.headerHight = this.$refs.refresh.headerHight
			}
			this.$refs.pageSwiper.swiperTo(e)
			//#endif
		},
		// 监听banner滑动 ??
		swiperChange(e) {
			//#ifndef MP-WEIXIN
			this.$store.commit('setChangeIndex', e)
			if (e === 0) {
				this.$refs.addCar.getHight()
				this.headerHight = this.$refs.addCar.headerHight
			} else {
				this.$refs.refresh.getHight()
				this.headerHight = this.$refs.refresh.headerHight
			}
			//#endif
		},
		//首页下拉刷新
		onPullDownRefresh() {
			this.getLocation()
			if (this.swiperCurrent === 1) {
				this.$refs.refresh.carlist = {
					0: [],
					1: [],
					2: [],
					3: []
				}
				this.$refs.refresh.pageNows = [1, 1, 1, 1]
				this.$refs.refresh.buyList()

			} else {
				this.$refs.addCar.list = []
				this.$refs.addCar.storeList = []
				this.$refs.addCar.getCardList()
				// this.$refs.addCar.getBuyDiscountsList()
				this.$refs.addCar.getMaintainStoreList()
			}
		},
		//移除区间事件
		comunicationOff() {
			uni.$off('rangeValues3')
		},
		//跳转
		goPages(url) {
			uni.navigateTo({
				url: url
			})
		},
		//下拉关闭
		close(e) {
			this.isOpen = false
		},
		//下拉列表打开
		open(e) {
			this.tapscroll()
			this.isOpen = true
		},
		//swiper切换
		listSwitch(index) {
			this.swiperCurrent = index.detail.current
		},

		
		// tim ready
		timReady() {

		},

		// 查询是否有进行中的洗车单
		hasWashingOrder() {
			this.$api.selfServiceCarWash.getCheckMyInProgressOrder().then(res => {
				if (res.code === 200 && res.data &&
					res.data.selfServiceCarWashOrder) {
					this.isWashing = true
					this.washCardId = res.data.selfServiceCarWashOrder.self_Service_Car_Wash_Card_Order_Id
					this.washMachineId = res.data.selfServiceCarWashOrder.wash_Machine_Id
					this.diffTime = dayjs(dayjs()).diff(
						dayjs(res.data.selfServiceCarWashOrder.use_Start_Time),
						'second'
					)
					this.washTimer = setInterval(() => {
						this.diffTime++
						if (this.diffTime < 3601) {
							const min =
								parseInt(this.diffTime / 60) > 9 ?
								parseInt(this.diffTime / 60) :
								'0' + parseInt(this.diffTime / 60)
							const secend =
								this.diffTime % 60 > 9 ?
								this.diffTime % 60 :
								'0' + (this.diffTime % 60)
							this.washingTime = min + ':' + secend
						} else {
							this.washingTime = ''
							clearInterval(this.washTimer)
						}
					}, 1000)
				} else {
					this.isWashing = false
					if (this.washTimer) {
						this.washingTime = ''
						clearInterval(this.washTimer)
					}
				}
			}).catch(() => {
				this.isWashing = false
				if (this.washTimer) {
					this.washingTime = ''
					clearInterval(this.washTimer)
				}
			})
		},
		// 结束洗车订单
		async setSailJiesuan() {
			try {
				uni.showLoading({
					title: '结束中...'
				})
				let res = await this.$api.selfServiceCarWash.SetSailJiesuan({
					wash_Machine_Id: this.washMachineId,
				})
				uni.hideLoading()
				if (res && res.code === 200 && res.data.result === 'success') {
					uni.showToast({
						icon: 'none',
						title: '结束成功',
					})
					this.isWashing = false
					clearInterval(this.washTimer)
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg,
					})
				}
			} catch (e) {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: e.msg,
				})
			}
		},
		//跳转洗车订单详情
		orderDetial() {
			uni.navigateTo({
				url: '/pages_commodity/selfWash/index?cardId=' + this.washCardId + '&machineId=' + this
					.washMachineId
			})
		}

	},
}
